package com.test.dataSource.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(1)
public class DataSourceAspect {
    @Pointcut("@within(com.test.dataSource.config.SwitchDataSource) " +
            "|| @annotation(com.test.dataSource.config.SwitchDataSource)")
    public void dataSourcePointCut() {
    }

    @Before("dataSourcePointCut()")
    public void doBefore(JoinPoint joinPoint){
        boolean clear = false;
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        SwitchDataSource annotationClass = method.getAnnotation(SwitchDataSource.class);//获取方法上的注解
        clear = annotationClass.clear();
        if(annotationClass == null){
            annotationClass = joinPoint.getTarget().getClass().getAnnotation(SwitchDataSource.class);//获取类上面的注解
            if(annotationClass == null){
                return;
            }
        }
        System.out.println("11111111");
        //获取注解上的数据源的值的信息
        String dataSourceKey = annotationClass.dataSource();
        if(dataSourceKey !=null){
            //给当前的执行SQL的操作设置特殊的数据源的信息
            String dataSourceKey0 = DataSourceName.queryKeyByValue(dataSourceKey);
            DataSourceHolder.setDataSourceKey(dataSourceKey0);
        }
    }

    @After("dataSourcePointCut()")
    protected void after() {
        DataSourceHolder.clearDataSourceKey();
    }
}
